package com.lyx.crm.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyx.crm.base.BaseService;
import com.lyx.crm.dao.ModuleMapper;
import com.lyx.crm.dao.PermissionMapper;
import com.lyx.crm.dao.RoleMapper;
import com.lyx.crm.query.RoleQuery;
import com.lyx.crm.query.UserQuery;
import com.lyx.crm.utils.AssertUtil;
import com.lyx.crm.vo.Permission;
import com.lyx.crm.vo.Role;
import com.lyx.crm.vo.SaleChance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Package: com.lyx.crm.service
 * @ClassName: RoleService
 * @Author: lyx
 * @CreateTime: 2021/8/28 19:25
 * @Description:
 */
@Service
public class RoleService extends BaseService<Role, Integer> {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ModuleMapper moduleMapper;

    public List<Map<String, Object>> queryAllRolesByUserId(Integer userId) {
        return roleMapper.queryAllRolesByUserId(userId);
    }

    public Map<String, Object> queryByParamsForTable(RoleQuery roleQuery) {
        Map<String, Object> map = new HashMap<>();

        //开启分页
        PageHelper.startPage(roleQuery.getPage(), roleQuery.getLimit());
        //得到对应分页对象
        PageInfo<Role> pageInfo = new PageInfo<>(roleMapper.selectByParams(roleQuery));

        //设置map对象
        map.put("code", 0);
        map.put("msg", "success");
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());

        return map;
    }

    /**
     * 添加角色信息
     *
     * @param role
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void addRole(Role role) {
        AssertUtil.isTrue(role.getRoleName() == null, "角色名不能为空");

        Role temp = roleMapper.selectByRoleName(role.getRoleName());
        AssertUtil.isTrue(temp != null, "角色姓名已存在，请重新输入");

        role.setCreateDate(new Date());
        role.setUpdateDate(new Date());
        role.setIsValid(1);
        AssertUtil.isTrue(roleMapper.insertSelective(role) <= 0, "添加角色失败");
    }


    /**
     * 修改角色信息
     *
     * @param role
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateRole(Role role) {
        //判断id ，并查询是否存在该id
        AssertUtil.isTrue(role.getId() == null, "角色Id不能为空");
        Role temp = roleMapper.selectByPrimaryKey(role.getId());
        AssertUtil.isTrue(temp == null, "待更新角色不存在");

        //判断名称是否重复
        AssertUtil.isTrue(role.getRoleName() == null, "角色名不能为空");
        temp = roleMapper.selectByRoleName(role.getRoleName());
        //判断角色记录是否存在（如果不存在，表示可使用，如果存在，且角色id与当前更新的角色ID不一致，表示该名称不可使用）
        AssertUtil.isTrue(null != temp && (!role.getId().equals(temp.getId())), "该名称已使用");

        role.setUpdateDate(new Date());
        AssertUtil.isTrue(roleMapper.updateByPrimaryKeySelective(role) < 1, "修改角色失败");
    }

    public void deleteRoleById(Integer roleId) {
        AssertUtil.isTrue(roleId == null, "待删除角色不存在");

        AssertUtil.isTrue(roleMapper.deleteByPrimaryKey(roleId) < 1, "删除角色失败");
    }

    /**
     * 添加权限资源
     * 1.判断该角色下是否有资源权限
     * 2.删除该角色拥有的所有资源权限
     * 3.根据mIds添加该角色的资源权限
     *
     * @param roleId
     * @param mIds
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void addGrant(Integer roleId, Integer[] mIds) {
        //1.判断该角色下是否有资源权限
        Integer count = permissionMapper.countPermissionByRoleId(roleId);
        //2.如果权限记录存在，则删除对应的角色拥有的权限记录
        if (count > 0) {
            permissionMapper.deletePermissionByRoleId(roleId);
        }
        //3.根据mIds添加该角色的资源权限
        if (mIds != null && mIds.length > 0) {

            //定义Permission集合
            List<Permission> permissionList = new ArrayList<>();

            //遍历资源ID数组
            for (Integer mId : mIds) {
                Permission permission = new Permission();
                permission.setModuleId(mId);
                permission.setRoleId(roleId);
                permission.setAclValue(moduleMapper.selectByPrimaryKey(mId).getOptValue());
                permission.setCreateDate(new Date());
                permission.setUpdateDate(new Date());

                //将对象放入集合中
                permissionList.add(permission);
            }
            AssertUtil.isTrue(permissionMapper.insertBatch(permissionList) != permissionList.size(), "添加权限资源失败");
        }

    }
}
